import React,{useEffect, useState} from 'react'
import { NavBar,ProductCard } from 'react-vant'
import { useNavigate } from 'react-router-dom'
import {debounce} from 'lodash'
import axios from 'axios';
import './index.css'
export default function SearchC() {
  const navigate=useNavigate()
  const [list,setList]=useState([])
  const [flist,setFlist]=useState([])
  let [lsjl,setLsjl]=useState([])
  useEffect(()=>{
    axios.get('/api/search').then((resp)=>{
        setList(resp.data.list)
        setFlist(resp.data.list)
    })
  },[])
  // 添加防抖
  const ss=debounce(()=>{
    let val=document.querySelector('.input').value
    if (val!=='') {
        // 搜索功能
        let item=list.filter((item)=>item.title.includes(val))
        // 添加到历史记录中
        lsjl.unshift(val)
        setList(item)
    }else{
        setList(flist)
    }
  },2000)
  const qk=()=>{
    setLsjl([])
  }
  return (
    <div>
      <NavBar
        title="搜索"
        leftText="返回"
        onClickLeft={() => navigate('/zhut/home')}
      />
      <div className='sbox'>
        <input type="text" placeholder='请输入搜索的内容' className='input' onInput={()=>ss()}/>
        <button className='sbtn' onClick={()=>ss()}>搜索</button>
      </div>
      <div className='jl'> 
        历史记录
        <span onClick={()=>qk()}>清空记录</span>
        <div>{lsjl.length>0 ? lsjl.map((item,ind)=><span key={ind}>{item}</span>):('没有搜索记录')}</div>
      </div>
      <div className='nrk'>
      {list.length>0 && list.map((item,ind)=>{
        return <div key={ind}>
            <ProductCard
            price={item.price}
            desc={item.word}
            title={item.title}
            thumb={item.img}
            />
        </div>
      })}
      </div>
    </div>
  )
}
